//
//  CHSViewController.m
//  CAIImagePickerController
//
//  Created by 海参 on 08/18/2021.
//  Copyright (c) 2021 海参. All rights reserved.
//

#import "CHSViewController.h"
#import <PhotosUI/PhotosUI.h>
#import <CAIImagePickerControllerKit/CAIImagePickerControllerKit.h>
#import <ZXCategoriesUtil/CAICategories.h>

@interface CHSViewController ()<
TZImagePickerControllerDelegate,
UINavigationControllerDelegate> {

    
}

@property (nonatomic, assign)BOOL isSelectOriginalPhoto;

@property (nonatomic, strong) NSMutableArray *selectedPhotos;
@property (nonatomic, strong) NSMutableArray *selectedAssets;

@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;

// 设置开关

///< 允许拍照
@property (weak, nonatomic) IBOutlet UISwitch *showTakePhotoBtnSwitch;

///< 允许拍视频
@property (weak, nonatomic) IBOutlet UISwitch *showTakeVideoBtnSwitch;

///< 照片排列按修改时间升序
@property (weak, nonatomic) IBOutlet UISwitch *sortAscendingSwitch;

///< 允许选择视频
@property (weak, nonatomic) IBOutlet UISwitch *allowPickingVideoSwitch;

///< 允许选择图片
@property (weak, nonatomic) IBOutlet UISwitch *allowPickingImageSwitch;

@property (weak, nonatomic) IBOutlet UISwitch *allowPickingGifSwitch;

///< 允许选择原图
@property (weak, nonatomic) IBOutlet UISwitch *allowPickingOriginalPhotoSwitch;

///< 显示一个sheet,把拍照/拍视频按钮放在外面
@property (weak, nonatomic) IBOutlet UISwitch *showSheetSwitch;

///< 照片最大可选张数，设置为1即为单选模式
@property (weak, nonatomic) IBOutlet UITextField *maxCountTextField;
/// 几列
@property (weak, nonatomic) IBOutlet UITextField *columnNumberTextField;


@property (weak, nonatomic) IBOutlet UISwitch *allowCropSwitch;
@property (weak, nonatomic) IBOutlet UISwitch *needCircleCropSwitch;
@property (weak, nonatomic) IBOutlet UISwitch *allowPickingMuitlpleVideoSwitch;

/// 是否显示选中索引
@property (weak, nonatomic) IBOutlet UISwitch *showSelectedIndexSwitch;


@end

@implementation CHSViewController

#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"


- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.selectedPhotos = [NSMutableArray array];
    self.selectedAssets = [NSMutableArray array];
}


- (BOOL)prefersStatusBarHidden {
    return NO;
}


- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
}






#pragma mark ------

- (IBAction)pickPhotoAction:(id)sender {   
    [self pushImagePickerController2];
}


- (void)pushImagePickerController2
{
    if (self.maxCountTextField.text.integerValue <= 0) {
        return;
    }
    TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:self.maxCountTextField.text.integerValue columnNumber:self.columnNumberTextField.text.integerValue delegate:self];
        
    if (self.maxCountTextField.text.integerValue > 1) {
        // 1.设置目前已经选中的图片数组
        imagePickerVc.selectedAssets = self.selectedAssets; // 目前已经选中的图片数组
    }
    
    // 1.在内部显示拍照按钮
    imagePickerVc.allowTakePicture = self.showTakePhotoBtnSwitch.isOn;
    imagePickerVc.allowTakeVideo = self.showTakeVideoBtnSwitch.isOn;

    // 2. 照片排列按修改时间升序
    imagePickerVc.sortAscendingByModificationDate = self.sortAscendingSwitch.isOn;

    // 3-4-5-6 设置是否可以选择视频/图片/原图
    imagePickerVc.allowPickingVideo = self.allowPickingVideoSwitch.isOn;
    imagePickerVc.allowPickingImage = self.allowPickingImageSwitch.isOn;
    imagePickerVc.allowPickingOriginalPhoto = self.allowPickingOriginalPhotoSwitch.isOn;
    imagePickerVc.allowPickingGif = self.allowPickingGifSwitch.isOn;
  
//

    
    imagePickerVc.allowPickingMultipleVideo = self.allowPickingMuitlpleVideoSwitch.isOn; // 是否可以多选视频
    
    // .设置是否显示图片序号
    imagePickerVc.showSelectedIndex = self.showSelectedIndexSwitch.isOn;
        
//
//     单选模式,maxImagesCount为1时才生效
//    imagePickerVc.showSelectBtn = NO;
    imagePickerVc.allowCrop = self.allowCropSwitch.isOn;
    imagePickerVc.needCircleCrop = self.needCircleCropSwitch.isOn;
    // 设置竖屏下的裁剪尺寸
    NSInteger left = 30;
    NSInteger widthHeight = [UIScreen mainScreen].bounds.size.width - 2 * left;
    NSInteger top = ([UIScreen mainScreen].bounds.size.height - widthHeight) / 2;
    imagePickerVc.cropRect = CGRectMake(left, top, widthHeight, widthHeight);
    imagePickerVc.scaleAspectFillCrop = YES;
    
    // 设置横屏下的裁剪尺寸
    // imagePickerVc.cropRectLandscape = CGRectMake((self.view.tz_height - widthHeight) / 2, left, widthHeight, widthHeight);
    /*
     [imagePickerVc setCropViewSettingBlock:^(UIView *cropView) {
     cropView.layer.borderColor = [UIColor redColor].CGColor;
     cropView.layer.borderWidth = 2.0;
     }];*/
    
    // imagePickerVc.allowPreview = NO;
    // 自定义导航栏上的返回按钮
    /*
    [imagePickerVc setNavLeftBarButtonSettingBlock:^(UIButton *leftButton){
        [leftButton setImage:[UIImage imageNamed:@"back"] forState:UIControlStateNormal];
        [leftButton setImageEdgeInsets:UIEdgeInsetsMake(0, -10, 0, 20)];
    }];
    imagePickerVc.delegate = self;
    */
    

    //
    imagePickerVc.iconThemeColor = [UIColor colorWithRed:31 / 255.0 green:185 / 255.0 blue:34 / 255.0 alpha:1.0];
    imagePickerVc.showPhotoCannotSelectLayer = YES;
    imagePickerVc.cannotSelectLayerColor = [[UIColor whiteColor] colorWithAlphaComponent:0.8];
    /*
    [imagePickerVc setPhotoPickerPageUIConfigBlock:^(UICollectionView *collectionView, UIView *bottomToolBar, UIButton *previewButton, UIButton *originalPhotoButton, UILabel *originalPhotoLabel, UIButton *doneButton, UIImageView *numberImageView, UILabel *numberLabel, UIView *divideLine) {
        [doneButton setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    }];
     */
    /*
    [imagePickerVc setAssetCellDidSetModelBlock:^(CAIAssetCell *cell, UIImageView *imageView, UIImageView *selectImageView, UILabel *indexLabel, UIView *bottomView, UILabel *timeLength, UIImageView *videoImgView) {
        cell.contentView.clipsToBounds = YES;
        cell.contentView.layer.cornerRadius = cell.contentView.tz_width * 0.5;
    }];
     */
    
    imagePickerVc.statusBarStyle = UIStatusBarStyleLightContent;
    

    
    // 你可以通过block或者代理，来得到用户选择的照片.
    [imagePickerVc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {

    }];
    
    imagePickerVc.modalPresentationStyle = UIModalPresentationFullScreen;
    [self presentViewController:imagePickerVc animated:YES completion:nil];
}




- (void)previewBtnAction:(NSIndexPath *)indexPath{
    
    if (self.selectedAssets.count <= indexPath.item) {
        return;
    }
    PHAsset *asset = self.selectedAssets[indexPath.item];
    BOOL isVideo = NO;
//    isVideo = asset.mediaType == PHAssetMediaTypeVideo;
    
    
    TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithSelectedAssets:self.selectedAssets selectedPhotos:self.selectedPhotos index:indexPath.item];
    imagePickerVc.delegate = self;
    imagePickerVc.maxImagesCount = 3;
    [imagePickerVc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
        self.selectedPhotos = [NSMutableArray arrayWithArray:photos];
        self.selectedAssets = [NSMutableArray arrayWithArray:assets];
        self.isSelectOriginalPhoto = isSelectOriginalPhoto;
    }];
    imagePickerVc.modalPresentationStyle = UIModalPresentationFullScreen;
    [self presentViewController:imagePickerVc animated:YES completion:nil];
    return;
 
}




/*
// 设置了navLeftBarButtonSettingBlock后，需打开这个方法，让系统的侧滑返回生效
- (void)navigationController:(UINavigationController *)navigationController didShowViewController:(UIViewController *)viewController animated:(BOOL)animated {
 
    navigationController.interactivePopGestureRecognizer.enabled = YES;
    if (viewController != navigationController.viewControllers[0]) {
        navigationController.interactivePopGestureRecognizer.delegate = nil; // 支持侧滑
    }
}
*/

#pragma mark - UIImagePickerController



// 调用相机
- (void)pushImagePickerController {
    __weak typeof(self) weakSelf = self;

//    UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
//    if ([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera]) {
//        self.imagePickerVc.sourceType = sourceType;
//        NSMutableArray *mediaTypes = [NSMutableArray array];
//        if (self.showTakeVideoBtnSwitch.isOn) {
//            [mediaTypes addObject:(NSString *)kUTTypeMovie];
//        }
//        if (self.showTakePhotoBtnSwitch.isOn) {
//            [mediaTypes addObject:(NSString *)kUTTypeImage];
//        }
//        if (mediaTypes.count) {
//            _imagePickerVc.mediaTypes = mediaTypes;
//        }
//        [self presentViewController:_imagePickerVc animated:YES completion:nil];
//    } else {
//        NSLog(@"模拟器中无法打开照相机,请在真机中使用");
//    }
}

- (void)imagePickerController:(UIImagePickerController*)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    [picker dismissViewControllerAnimated:YES completion:nil];
//    NSString *type = [info objectForKey:UIImagePickerControllerMediaType];
    

}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    if ([picker isKindOfClass:[UIImagePickerController class]]) {
        [picker dismissViewControllerAnimated:YES completion:nil];
    }
}

#pragma mark - TZImagePickerControllerDelegate

/// User click cancel button
/// 用户点击了取消
- (void)caiImagePickerControllerDidCancel:(TZImagePickerController *)picker {
    // NSLog(@"cancel");
}


// 这个照片选择器会自己dismiss，当选择器dismiss的时候，会执行下面的代理方法
// 你也可以设置autoDismiss属性为NO，选择器就不会自己dismis了
// 如果isSelectOriginalPhoto为YES，表明用户选择了原图
// 你可以通过一个asset获得原图，通过这个方法：[[TZImageManager manager] getOriginalPhotoWithAsset:completion:]
// photos数组里的UIImage对象，默认是828像素宽，你可以通过设置photoWidth属性的值来改变它
- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingPhotos:(NSArray<UIImage *> *)photos sourceAssets:(NSArray *)assets isSelectOriginalPhoto:(BOOL)isSelectOriginalPhoto infos:(NSArray<NSDictionary *> *)infos
{
    self.selectedPhotos = [NSMutableArray arrayWithArray:photos];
    self.selectedAssets = [NSMutableArray arrayWithArray:assets];
    self.isSelectOriginalPhoto = isSelectOriginalPhoto;

}

/// 如果用户选择了某张照片下面的代理方法会被执行;
/// 如果isSelectOriginalPhoto为YES，表明用户选择了原图
/// 你可以通过一个asset获得原图，通过这个方法：[[TZImageManager manager] getOriginalPhotoWithAsset:completion:]
- (void)imagePickerController:(TZImagePickerController *)picker didSelectAsset:(PHAsset *)asset photo:(UIImage *)photo isSelectOriginalPhoto:(BOOL)isSelectOriginalPhoto {

}

/// 如果用户取消选择了某张照片下面的代理方法会被执行；
/// 如果isSelectOriginalPhoto为YES，表明用户选择了原图
/// 你可以通过一个asset获得原图，通过这个方法：[[TZImageManager manager] getOriginalPhotoWithAsset:completion:]
- (void)imagePickerController:(TZImagePickerController *)picker didDeselectAsset:(PHAsset *)asset photo:(UIImage *)photo isSelectOriginalPhoto:(BOOL)isSelectOriginalPhoto {

}








// 如果用户选择了一个gif图片且allowPickingMultipleVideo是NO，下面的代理方法会被执行
// 如果allowPickingMultipleVideo是YES，将会调用imagePickerController:didFinishPickingPhotos:sourceAssets:isSelectOriginalPhoto:
- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingGifImage:(UIImage *)animatedImage sourceAssets:(PHAsset *)asset {
    
    self.selectedPhotos = [NSMutableArray arrayWithArray:@[animatedImage]];
    self.selectedAssets = [NSMutableArray arrayWithArray:@[asset]];
}



#pragma mark - Click Event

- (IBAction)showTakePhotoBtnSwitchClick:(UISwitch *)sender {
    if (sender.isOn) {
        [_allowPickingImageSwitch setOn:YES animated:YES];
    }
}

- (IBAction)showTakeVideoBtnSwitchClick:(UISwitch *)sender {
    if (sender.isOn) {
        [_allowPickingVideoSwitch setOn:YES animated:YES];
    }
}

- (IBAction)showSheetSwitchClick:(UISwitch *)sender {
    if (sender.isOn) {
        [_allowPickingImageSwitch setOn:YES animated:YES];
    }
}

- (IBAction)allowPickingOriginPhotoSwitchClick:(UISwitch *)sender {
    if (sender.isOn) {
        [_allowPickingImageSwitch setOn:YES animated:YES];
        [self.needCircleCropSwitch setOn:NO animated:YES];
        [self.allowCropSwitch setOn:NO animated:YES];
    }
}

- (IBAction)allowPickingImageSwitchClick:(UISwitch *)sender {
    if (!sender.isOn) {
        [_allowPickingOriginalPhotoSwitch setOn:NO animated:YES];
        [_allowPickingVideoSwitch setOn:YES animated:YES];
        [_allowPickingGifSwitch setOn:NO animated:YES];
    }
}

- (IBAction)allowPickingGifSwitchClick:(UISwitch *)sender {
    if (sender.isOn) {
        [_allowPickingImageSwitch setOn:YES animated:YES];
    } else if (!self.allowPickingVideoSwitch.isOn) {
        [self.allowPickingMuitlpleVideoSwitch setOn:NO animated:YES];
    }
}

- (IBAction)allowPickingVideoSwitchClick:(UISwitch *)sender {
    if (!sender.isOn) {
        [_allowPickingImageSwitch setOn:YES animated:YES];
        if (!self.allowPickingGifSwitch.isOn) {
            [self.allowPickingMuitlpleVideoSwitch setOn:NO animated:YES];
        }
    }
}

- (IBAction)allowCropSwitchClick:(UISwitch *)sender {
    if (sender.isOn) {
        self.maxCountTextField.text = @"1";
        [self.allowPickingOriginalPhotoSwitch setOn:NO animated:YES];
    } else {
        if ([self.maxCountTextField.text isEqualToString:@"1"]) {
            self.maxCountTextField.text = @"9";
        }
        [self.needCircleCropSwitch setOn:NO animated:YES];
    }
}

- (IBAction)needCircleCropSwitchClick:(UISwitch *)sender {
    if (sender.isOn) {
        [self.allowCropSwitch setOn:YES animated:YES];
        self.maxCountTextField.text = @"1";
        [self.allowPickingOriginalPhotoSwitch setOn:NO animated:YES];
    }
}

- (IBAction)allowPickingMultipleVideoSwitchClick:(UISwitch *)sender {
 
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self.view endEditing:YES];
}



#pragma clang diagnostic pop

@end
